Issuer = new Object();

var issuer_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'address', 'code', 'creditRating', 'name', 'email', 'fax', 'phone', 'ratingGivenBy', 'issuerTypeId', 'companyRegNo' ]
});

var issuer_category_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'code', 'issureCategory', 'primaryDealer' ],
});

var credit_rating_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'code', 'creditRating', 'ratingValue' ]
});
var issuer_id = null;
var issuer_bank_account_store = Ext.create('Ext.data.Store', {
	fields : [ 'id', 'nameOfBank', 'barnch', 'accountNo' ]
});

var issuer_contact_person_store = Ext.create('Ext.data.Store', {
	fields : [ 'cpName', 'cpDesignation', 'cpPhone', 'cpFax', 'cpEmail' ]
});

Issuer.getContactPerson = function() {
	var grid = null;
	grid = Ext.create('Ext.grid.Panel', {
		store : issuer_contact_person_store,
		id : 'issuer_contact_perons',
		layout : {
			type : 'fit'
		},
		height : 135,
		anchor : '100%',
		columns : [ {
			header : 'Name',
			dataIndex : 'cpName',
			width : 140,
			flex : 1
		}, {
			header : 'Designation',
			dataIndex : 'cpDesignation',
			width : 140,
			flex : 1
		}, {
			header : 'Phone',
			dataIndex : 'cpPhone',
			width : 100
		}, {
			header : 'Fax',
			dataIndex : 'cpFax',
			width : 100
		}, {
			header : 'Email',
			dataIndex : 'cpEmail',
			width : 150
		} ],
		dockedItems : [ {
			xtype : 'toolbar',
			dock : 'top',
			items : [ '->', {
				xtype : 'button',
				text : 'Add',
				listeners : {
					click : function() {
						var formContactPerson = Ext.getCmp('contactPerson').getForm();
						if (formContactPerson.isValid()) {
							issuer_contact_person_store.add({
								cpName : Ext.getCmp('cpName').getValue(),
								cpDesignation : Ext.getCmp('cpDesignation').getValue(),
								cpPhone : Ext.getCmp('cpPhone').getValue(),
								cpFax : Ext.getCmp('cpFax').getValue(),
								cpEmail : Ext.getCmp('cpEmail').getValue()
							});
							formContactPerson.reset();
						}
					}
				}
			}, {
				xtype : 'button',
				text : 'Remove',
				listeners : {
					click : function() {
						var selection = grid.getView().getSelectionModel().getSelection()[0];
						if (selection) {
							issuer_contact_person_store.remove(selection);
						}
					}
				}
			} ]
		} ]
	});
	return Ext.create('Ext.form.FieldSet', {
		title : 'Contact Persons',
		defaults : {
			anchor : '100%'
		},
		items : [ {
			xtype : 'form',
			bodyBorder : false,
			frame : true,
			border : false,
			id : 'contactPerson',
			fieldDefaults : {
				labelAlign : 'top'
			},
			layout : {
				type : 'hbox',
				align : 'stretch'
			},
			items : [ {
				xtype : 'textfield',
				id : 'cpName',
				msgTarget : 'side',
				fieldLabel : 'Name',
				padding : '0 2 0 0',
				flex : 1
			}, {
				xtype : 'textfield',
				fieldLabel : 'Designation',
				padding : '0 2 0 0',
				id : 'cpDesignation',
				flex : 1
			}, {
				xtype : 'textfield',
				fieldLabel : 'Phone',
				id : 'cpPhone',
				padding : '0 2 0 0',
				maskRe : /[\d]/
			}, {
				xtype : 'textfield',
				fieldLabel : 'Fax',
				id : 'cpFax',
				padding : '0 2 0 0',
				maskRe : /[\d]/
			}, {
				xtype : 'textfield',
				fieldLabel : 'E-mail',
				id : 'cpEmail',
				vtype : 'email',
				padding : '0 2 0 0',
			} ]
		}, grid ],

	});
};

Issuer.getBankAccountDetails = function() {

	var bankgrid = null;

	bankgrid = Ext.create('Ext.grid.Panel', {
		store : issuer_bank_account_store,
		layout : {
			type : 'fit'
		},
		height : 135,
		anchor : '100%',
		id : 'issuer_bank_account',
		columns : [ {
			header : 'Name of Bank',
			dataIndex : 'nameOfBank',
			width : 140,
			flex : 1
		}, {
			header : 'Branch',
			dataIndex : 'barnch',
			width : 140,
			flex : 1
		}, {
			header : 'Account No',
			dataIndex : 'accountNo',
			width : 100,
			flex : 1
		} ],
		dockedItems : [ {
			xtype : 'toolbar',
			dock : 'top',
			items : [ '->', {
				xtype : 'button',
				text : 'Add',
				listeners : {
					click : function() {
						var formbankAccount = Ext.getCmp('bankAccount').getForm();
						if (formbankAccount.isValid()) {
							issuer_bank_account_store.add({
								nameOfBank : Ext.getCmp('bname').getValue(),
								barnch : Ext.getCmp('barnch').getValue(),
								accountNo : Ext.getCmp('account').getValue(),
								id : 0
							});
							formbankAccount.reset();
						}
					}
				}
			}, {
				xtype : 'button',
				text : 'Remove',
				listeners : {
					click : function() {
						var selection = bankgrid.getView().getSelectionModel().getSelection()[0];
						if (selection) {
							issuer_bank_account_store.remove(selection);
						}
					}
				}
			} ]
		} ]
	});
	return Ext.create('Ext.form.FieldSet', {
		title : 'Bank Account',
		defaults : {
			anchor : '100%'
		},
		items : [ {
			xtype : 'form',
			bodyBorder : false,
			frame : true,
			border : false,
			id : 'bankAccount',
			fieldDefaults : {
				labelAlign : 'top'
			},
			layout : {
				type : 'hbox',
				align : 'stretch'
			},
			items : [ {
				xtype : 'textfield',
				id : 'bname',
				msgTarget : 'side',
				fieldLabel : 'Name of Bank',
				padding : '0 2 0 0',
				flex : 1
			}, {
				xtype : 'textfield',
				fieldLabel : 'Branch',
				padding : '0 2 0 0',
				id : 'barnch',
				flex : 1
			}, {
				xtype : 'textfield',
				fieldLabel : 'Account No',
				id : 'account',
				padding : '0 2 0 0'
			} ]
		}, bankgrid ],

	});
};

Issuer.getPersonalDetails = function() {

	return Ext.create('Ext.form.FieldSet', {
		defaults : {
			anchor : '100%'
		},
		items : [ {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'textfield',
				fieldLabel : 'Issuer Code<span style="color:red">*</span>',
				name : 'code',
				allowBlank : false,
				msgTarget : 'under',
				maxLength : 20,
				flex : 1
			}, {
				xtype : 'textfield',
				fieldLabel : 'Issuer Name<span style="color:red">*</span>',
				name : 'name',
				flex : 1,
				allowBlank : false,
				msgTarget : 'under',
				padding : '0 0 0 5'
			}, ]
		}, {
			xtype : 'textarea',
			fieldLabel : 'Address',
			height : 50,
			name : 'address'
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'textfield',
				fieldLabel : 'Phone',
				name : 'phone',
				padding : '0 5 0 0',
				flex : 1,
				msgTarget : 'under',
				minLength : 10,
				maskRe : /[\d]/
			}, {
				xtype : 'textfield',
				fieldLabel : 'Fax',
				name : 'fax',
				labelWidth : 40,
				padding : '0 5 0 0',
				flex : 1,
				msgTarget : 'under',
				maskRe : /[\d]/,
				minLength : 10
			}, {
				xtype : 'textfield',
				fieldLabel : 'E-mail',
				vtype : 'email',
				vtypeText : 'Please enter a valid email address',
				labelWidth : 50,
				msgTarget : 'under',
				name : 'email',
				flex : 1
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'combo',
				fieldLabel : 'Issuer Category<span style="color:red">*</span>',
				valueField : 'id',
				store : issuer_category_store,
				queryMode : 'local',
				msgTarget : 'under',
				displayField : 'issureCategory',
				isLoaded : false,
				flex : 1,
				padding : '0 5 0 0',
				allowBlank : false,
				name : 'issuerTypeId',
				emptyText : 'Select a Issuer Category...',
				listeners : {
					expand : function(combo, opt) {
						if (!combo.isLoaded) {
							Ext.Ajax.request({
								url : 'getAllIssuerTypes.action',
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									combo.getStore().loadRawData(obj.issuerTypeDtos);
									combo.isLoaded = true;
								}
							});
						}
					}
				}
			}, {
				xtype : 'textfield',
				fieldLabel : 'Company Registration No.',
				flex : 1,
				name : 'companyRegNo'
			} ]
		}, {
			xtype : 'fieldcontainer',
			layout : 'hbox',
			items : [ {
				xtype : 'combo',
				fieldLabel : 'Credit Rating',
				queryMode : 'local',
				store : credit_rating_store,
				valueField : 'id',
				displayField : 'creditRating',
				flex : 1,
				id : 'creditrating',
				name : 'creditRating',
				padding : '0 5 0 0',
				emptyText : 'Select a Credit Rating...',
				listeners : {
					expand : function(combo, opt) {
						if (!combo.isLoaded) {
							Ext.Ajax.request({
								url : 'getAllCreditRates.action',
								success : function(response) {
									var obj = Ext.decode(response.responseText);
									combo.getStore().loadRawData(obj.creditRatingDtos);
									combo.isLoaded = true;
								}
							});
						}
					}
				}
			}, {
				xtype : 'textfield',
				fieldLabel : 'Rating Given By',
				flex : 1,
				name : 'ratingGivenBy'
			} ]
		} ]
	});
};

Issuer.getCenterPanel = function() {

	issuer_bank_account_store.removeAll();
	issuer_contact_person_store.removeAll();

	var personaldetails = Issuer.getPersonalDetails();
	var contactPerson = Issuer.getContactPerson();
	var bankAccountDetails = Issuer.getBankAccountDetails();
	return formPanel = Ext.create('Ext.form.FormPanel', {
		title : 'Issuer',
		bodyPadding : 20,
		autoScroll : true,
		defaults : {
			labelWidth : 175,
			anchor : '65%'
		},
		frame : true,
		id : 'issuer_form',
		items : [ {
			xtype : 'fieldcontainer',
			items : [ {
				xtype : 'triggerfield',
				emptyText : 'Search Issuer',
				triggerCls : 'x-form-search-trigger',
				width : 300,
				style : 'float:right;',
				listeners : {
					specialkey : function(field, e) {
						if (e.getKey() == e.ENTER) {
							Ext.MessageBox.show({
								title : 'Issuer',
								msg : 'Invalid Code',
								buttons : Ext.MessageBox.OK,
								icon : Ext.MessageBox.INFO
							});
						}
					}
				},
				onTriggerClick : function() {
					var window = null;
					Ext.Ajax.request({
						url : 'getAllIssuers.action',
						success : function(response) {
							var obj = Ext.decode(response.responseText);
							issuer_store.loadRawData(obj.issuerDtos);
						}
					});
					if (!window) {
						window = Ext.create('Ext.window.Window', {
							title : 'Issuer',
							height : 330,
							frame : true,
							width : 500,
							modal : true,
							constrain : true,
							resizable : false,
							layout : {
								type : 'fit'
							},
							items : [ {
								xtype : 'gridpanel',
								defaults : {
									anchor : '100%'
								},
								store : issuer_store,
								columns : [ {
									text : 'Issuer Code',
									dataIndex : 'code',
									flex : 1
								}, {
									text : 'Issuer Name',
									dataIndex : 'name',
									flex : 1
								} ],
								listeners : {
									itemdblclick : function(dv, record, item, index, e) {
										Issuer.setDataToForm(record);
										window.hide();
									}
								}
							} ]
						});
					}
					if (window.isVisible()) {
						window.hide();
					} else {
						window.show();
					}
				}
			} ]
		}, personaldetails, contactPerson, bankAccountDetails ],
		buttonAlign : 'center',
		buttons : [ {
			text : 'Cancel',
			handler : function() {
				App.Core.removeScreen();
			}
		}, {
			text : 'Reset',
			handler : function() {
				this.up('form').getForm().reset();
				issuer_id = null;
				issuer_contact_person_store.removeAll();
				issuer_bank_account_store.removeAll();
				Ext.getCmp('save').setText('Save');
			}
		}, {
			text : 'Save',
			id : 'save',
			handler : function() {
				var form = this.up('form').getForm();
				if (form.isValid()) {
					formPanel.setLoading('Loading...');
					var bankAccountgrids = Ext.getCmp('issuer_bank_account');
					var acconts = new Array();
					bankAccountgrids.getStore().each(function(record) {
						var obj = {
							"id" : record.get("id"),
							"accountNo" : record.get("accountNo"),
							"barnch" : record.get("barnch"),
							"nameOfBank" : record.get("nameOfBank")
						};
						acconts.push(obj);
					});
					var contactpersons_form = Ext.getCmp('issuer_contact_perons');
					var con_person = new Array();
					contactpersons_form.getStore().each(function(record) {
						var obj = {
							"cpName" : record.get("cpName"),
							"cpDesignation" : record.get("cpDesignation"),
							"cpPhone" : record.get("cpPhone"),
							"cpFax" : record.get('cpFax'),
							"cpEmail" : record.get('cpEmail')
						};
						con_person.push(obj);
					});
					if (issuer_id == null) {
						if (acconts.length >= 1) {
							form.url = 'addIssuer.action';
							form.submit({
								params : {
									"bankAccounts" : Ext.encode(acconts),
									"contactPersons" : Ext.encode(con_person)
								},
								success : function(form, action) {
									form.reset();
									Ext.Msg.alert('Success', 'Saved Successfully');
									contactpersons_form.getStore().removeAll();
									bankAccountgrids.getStore().removeAll();
									formPanel.setLoading(false);
									issuer_id = null;
									Ext.getCmp('save').setText('Save');
								},
								failure : function(form, action) {
									Ext.Msg.alert('Failed', action.result.resultMsg);
									formPanel.setLoading(false);
								}
							});
						} else {
							formPanel.setLoading(false);
							Ext.Msg.alert('Failed', "Please Add one or more bank account details");
						}
					} else {
						if (acconts.length >= 1) {
							form.url = 'updateIssuer.action';
							form.submit({
								params : {
									"bankAccounts" : Ext.encode(acconts),
									"contactPersons" : Ext.encode(con_person),
									"issuerId" : issuer_id
								},
								success : function(form, action) {
									form.reset();
									Ext.Msg.alert('Success', 'Update Successfully');
									contactpersons_form.getStore().removeAll();
									bankAccountgrids.getStore().removeAll();
									formPanel.setLoading(false);
									issuer_id = null;
									Ext.getCmp('save').setText('Save');
								},
								failure : function(form, action) {
									Ext.Msg.alert('Failed', action.result.resultMsg);
									formPanel.setLoading(false);
								}
							});
						} else {
							formPanel.setLoading(false);
							Ext.Msg.alert('Failed', "Please Add one or more bank account details");
						}
					}
				}
			}
		} ],
		listeners : {
			render : function(p) {
				if (App.screenPermiton.getAt(0).data.create == 0)
					Ext.getCmp('save').disable();
				else
					Ext.getCmp('save').enable();
			}
		}
	});
};

Issuer.setDataToForm = function(data) {

	var formPanl = Ext.getCmp('issuer_form');
	issuer_contact_person_store.removeAll();
	issuer_bank_account_store.removeAll();
	formPanel.setLoading('Loading..', formPanl.getForm());
	issuer_id = data.data.id;
	Ext.Ajax.request({
		url : 'getAllIssuerTypes.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			issuer_category_store.loadRawData(obj.issuerTypeDtos);
		}
	});
	Ext.Ajax.request({
		url : 'getAllCreditRates.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			credit_rating_store.loadRawData(obj.creditRatingDtos);
			Ext.getCmp('creditrating').isLoaded = true;
		}
	});
	console.log(data);
	formPanl.getForm().loadRecord(data);
	Ext.Ajax.request({
		params : {
			"issuer_id" : issuer_id
		},
		url : 'getIssuerBankAccounts.action',
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			issuer_bank_account_store.loadRawData(obj.issuerBankAccountDtos);
		}
	});
	Ext.Ajax.request({
		url : 'getIssuerContactPerson.action',
		params : {
			"issuer_id" : issuer_id
		},
		success : function(response) {
			var obj = Ext.decode(response.responseText);
			issuer_contact_person_store.loadRawData(obj.contactPersonDtos);
		}
	});
	Ext.getCmp('save').setText('Update');
	formPanel.setLoading(false);
};
